package com.example.hotel_lxy.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.application.ARouterPath;
import com.example.hotel_lxy.bean.Bean;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.GetUserBean;
import com.example.hotel_lxy.bean.LoginBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.sql.UserDao;
import com.example.hotel_lxy.utils.DateUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.ysxsoft.common_base.base.BaseActivity;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 登录
 */
@Route(path = "/main/LoginActivity")
public class LoginActivity extends BaseActivity {

    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.edit_pass)
    EditText editPass;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.text_code)
    TextView textCode;
    @BindView(R.id.text_agreement)
    TextView textAgreement;
    @BindView(R.id.text_privacy)
    TextView textPrivacy;
    @BindView(R.id.text_login)
    TextView textLogin;
    private boolean isClicked = false;
    CountDownTimer timer;
    private UserDao demoDao;
    String currentDate;
    public static void start() {
        ARouter.getInstance().build(ARouterPath.getLoginActivity())
                .navigation();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void doWork() {
        super.doWork();

        demoDao = new UserDao(this);
        textAgreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        textPrivacy.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());//获取当前时间
        currentDate = simpleDateFormat.format(date);
        SPUtils.put(LoginActivity.this, "startTime", "");
        SPUtils.put(LoginActivity.this, "end_time", "");
        Log.e("TAG",SPUtils.get(LoginActivity.this,"token","").toString()+"  123");
        if(!SPUtils.get(LoginActivity.this,"token","").toString().equals("")){
            SPUtils.put(LoginActivity.this, "homeorder",  "#-#-#-#-#");
            SPUtils.put(LoginActivity.this, "currentDate", currentDate+"");
            showGetUser();
            MainActivity.start("0");
            finish();
        }
//        editName.setText("123456");
//        editPass.setText("12345");
//        editCode.setText("123456");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.text_code, R.id.text_agreement, R.id.text_privacy,R.id.text_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_code://获取验证码
//                if (!isPhone(editName.getText().toString())) {
//                    showToast("请填写手机号码！");
//                    return;
//                }
                showGetCode();
                break;
            case R.id.text_agreement://协议
                WebActivity.start("http://api.luxiaoyi.vip/about/1.html","用户协议");
                break;
            case R.id.text_privacy://隐私
                WebActivity.start("http://api.luxiaoyi.vip/about/2.html","隐私协议");
                break;
            case R.id.text_login:
                if (editName.getText().toString().equals("")) {
                    showToast("登录账号不能为空");
                    return;
                }
                if ("".equals(editPass.getText().toString())) {
                    showToast("密码不能为空！");
                    return;
                }
                if ("".equals(editCode.getText().toString())) {
                    showToast("请填写验证码！");
                    return;
                }
//                if (editCode.getText().toString().length()!=4) {
//                    showToast("请填写正确验证码！");
//                    return;
//                }
                getLogin();
                break;

        }
    }
    private void getLogin()     {
        showLoadingDialog("请求中");
        OkHttpUtils.post()
                .url(Api.POST_LOGIN)
                .addParams("mobile",editName.getText().toString().trim())
                .addParams("password",editPass.getText().toString().trim())
                .addParams("code",editCode.getText().toString().trim())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "登录Exception~~~~~~~~    " + e.getMessage());
                        hideLoadingDialog();

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideLoadingDialog();
                        Log.e("TAG", "登录onResponse~~~~~~~~    " + response);

                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("0")){
                            LoginBean loginBean = JsonUtils.parseByGson(response, LoginBean.class);
                            String phoneNumber = demoDao.getPhoneNumber(editName.getText().toString());
                            if (phoneNumber == null) {
                                demoDao.add(editName.getText().toString()+"", editPass.getText().toString()+"", loginBean.getData().getId()+"",
                                        loginBean.getData().getAvatar()+"",loginBean.getData().getMobile()+"",loginBean.getData().getToken()+"");
                            }else{
                                demoDao.update(editName.getText().toString()+"", editPass.getText().toString()+"", loginBean.getData().getId()+"",
                                        loginBean.getData().getAvatar()+"",loginBean.getData().getMobile()+"",loginBean.getData().getToken()+"");
                            }
                            SPUtils.put(LoginActivity.this,"token",""+loginBean.getData().getToken());
                            SPUtils.put(LoginActivity.this, "name", ""+editName.getText().toString());
                            SPUtils.put(LoginActivity.this, "names", ""+editName.getText().toString());
                            SPUtils.put(LoginActivity.this, "id", ""+loginBean.getData().getId());
                            SPUtils.put(LoginActivity.this, "mobile", ""+loginBean.getData().getMobile());
                            SPUtils.put(LoginActivity.this, "username", ""+loginBean.getData().getUsername());
                            SPUtils.put(LoginActivity.this, "currentDate", currentDate+"");
                            SPUtils.put(LoginActivity.this, "homeorder",  "#-#-#-#-#");
                            MainActivity.start("0");
                            if (timer != null) {
                                timer.cancel();
                                timer = null;
                            }
                            showGetUser();
                            finish();
                        }else{
                            ToastUtils.shortToast(LoginActivity.this,beanBean.getMsg());
                        }
                    }
                });
    }
    private void showGetCode() {
        if (!isClicked) {
            if (editName.getText().toString().equals("")) {
                showToast("请填写登录账号！");
                return;
            }
            isClicked = true;
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            timer = new CountDownTimer(60 * 1000, 1000) {
                //进行时
                public void onTick(long millisUntilFinished) {
                    textCode.setText((millisUntilFinished / 1000) + "秒倒计时");
                }

                //结束
                public void onFinish() {
                    textCode.setText("发送验证码");
                    isClicked = false;
                }
            };
            timer.start();
            showDataSendCode();
        }
    }

    private void showDataSendCode() {
        showLoadingDialog("请求中");
        OkHttpUtils.post()
                .url(Api.POST_SENDCODE)
                .addParams("mobile",editName.getText().toString())
                .addParams("password",editPass.getText().toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "验证码Exception~~~~~~~~    " + e.getMessage());
                        hideLoadingDialog();

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideLoadingDialog();
                        Log.e("TAG", "验证码onResponse~~~~~~~~    " + response);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("0")){
                            ToastUtils.shortToast(LoginActivity.this,beanBean.getMsg());
                        }else{
                            ToastUtils.shortToast(LoginActivity.this,beanBean.getMsg());
                            if (timer != null) {
                                timer.cancel();
                                timer = null;
                                textCode.setText("发送验证码");
                                isClicked = false;
                            }
                        }


                    }
                });
    }

    public static boolean isPhone(String phone) {
//        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(167)|(165)|(17[0,1,2,3,5,6,7,8])|(18[0-9])|(19[0-9]))\\d{8}$";
        if (phone.length() != 11) {

            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }

    private void showGetUser() {
        String string = SPUtils.get(LoginActivity.this, "token", "").toString();
        Log.e("TAG",string+"  123");
        OkHttpUtils.post()
                .url(Api.POST_USER_GETUSER)
                .addHeader("flag", SPUtils.get(LoginActivity.this, "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "个人信息Exception~~~~~~~~    " + e.getMessage());
                        hideLoadingDialog();
                        showGetUser();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "个人信息onResponse~~~~~~~~    " + response);
                        BeanBean beanBean = JsonUtils.parseObject(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            GetUserBean getUserBean = JsonUtils.parseObject(response, GetUserBean.class);
                            SPUtils.put(LoginActivity.this, "username", "" + getUserBean.getData().getList().getUsername());

                            SPUtils.put(LoginActivity.this, "hotel", "" + getUserBean.getData().getList().getHotel());
                            //仅查看销控表
                            SPUtils.put(LoginActivity.this, "xiaokongbiao", ""+getUserBean.getData().getRole().getXiaokongbiao()+"");
                            //是否开启零点功能  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "notenabled", "" + getUserBean.getData().getRole().getNotenabled());
                            //是否可以零点新增预定
                            SPUtils.put(LoginActivity.this, "addzero", "" + getUserBean.getData().getRole().getAddzero());
                            //选择客户经理
                            SPUtils.put(LoginActivity.this, "szkehujl", "" + getUserBean.getData().getRole().getSzkehujl());
                            //是否可以新增预定
                            SPUtils.put(LoginActivity.this, "addscheduled", "" + getUserBean.getData().getRole().getAddscheduled());
                            //仅查看零点销控表
                            SPUtils.put(LoginActivity.this, "jcklingdianck", "" + getUserBean.getData().getRole().getJcklingdianck());
                            //零点选择预订人
                            SPUtils.put(LoginActivity.this, "xzyudingren", "" + getUserBean.getData().getRole().getXzyudingren());
                            //不启用零点  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "notenabled", "" + getUserBean.getData().getRole().getNotenabled());
                            //零点查看全部  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "ldchakanqb", "" + getUserBean.getData().getRole().getLdchakanqb());
                            //是否可以零点修改个人  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "ldmodifypersonal", "" + getUserBean.getData().getRole().getLdmodifypersonal());
                            //是否可以零点修改全部  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "ldmodifyall", "" + getUserBean.getData().getRole().getLdmodifyall());
                            //是否可以零点退订全部  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "retreatall", "" + getUserBean.getData().getRole().getRetreatall());
                            //是否可以零点退订个人  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "retreatpersonal", "" + getUserBean.getData().getRole().getRetreatpersonal());
                            //是否可以零点入座全部  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "seatall", "" + getUserBean.getData().getRole().getSeatall());
                            //是否可以零点入座个人  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "seatpersonal", "" + getUserBean.getData().getRole().getSeatpersonal());
                            //是否可以零点翻台全部  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "overturnall", "" + getUserBean.getData().getRole().getOverturnall());
                            //是否可以零点翻台个人  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "overturnpersonal", "" + getUserBean.getData().getRole().getOverturnpersonal());
                            //查看全部营销订单1开启  0关闭
                            SPUtils.put(LoginActivity.this, "ckqbyingxiao", ""+getUserBean.getData().getRole().getCkqbyingxiao());
                            //是否可以查看全部  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "sayall", "" + getUserBean.getData().getRole().getSayall());
                            //是否可以查看个人  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "saypersonal", "" + getUserBean.getData().getRole().getSaypersonal());

                            //是否可以查看TOP榜  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "saytop", "" + getUserBean.getData().getRole().getSaytop());
                            //营销查看全部回访  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "sayvisitall", "" + getUserBean.getData().getRole().getSayvisitall());
                            //营销添加回访  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "addvisit", "" + getUserBean.getData().getRole().getAddvisit());

                            //查看全部宴会数据  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "saybanquetdata", "" + getUserBean.getData().getRole().getSaybanquetdata());
                            //查看全部零点数据  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "sayzerodata", "" + getUserBean.getData().getRole().getSayzerodata());
                            //查看全部宴会客户  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "banquetclient", "" + getUserBean.getData().getRole().getBanquetclient());
                            //查看全部零点客户  1开启  0关闭
                            SPUtils.put(LoginActivity.this, "zeroclient", "" + getUserBean.getData().getRole().getZeroclient());
                            //修改全部宴会客户
                            SPUtils.put(LoginActivity.this, "modifybanquet", "" + getUserBean.getData().getRole().getModifybanquet());
                            //修改全部零点客户
                            SPUtils.put(LoginActivity.this, "modifyzero", "" + getUserBean.getData().getRole().getModifyzero());

                            //收据编号
                            SPUtils.put(LoginActivity.this, "receipt_status", "" + getUserBean.getData().getReceipt_status());

                            //确认方式 // 1 多次  2  1次
                            SPUtils.put(LoginActivity.this, "config", ""+getUserBean.getData().getConfig());
                            SPUtils.put(LoginActivity.this, "hotel_mobile", "" + getUserBean.getData().getList().getHotel_mobile());

                            SPUtils.put(LoginActivity.this, "hotel_addr", "" + getUserBean.getData().getList().getHotel_addr());

                        }

                    }
                });
    }



}